<template>
	<div class="domain-management">
		<!-- 添加域名按钮 -->
		<div class="operation-row">
			<el-button type="primary" @click="showAddDomainDialog">添加域名</el-button>
		</div>

		<!-- 统计信息和搜索 -->
		<div class="search-row">
			<div class="search-input">
				<el-input v-model="searchDomain" placeholder="请输入域名名称" />
			</div>
			<el-button type="primary" @click="handleSearch">搜索</el-button>
		</div>

		<!-- 表格 -->
		<el-table :data="tableData" border style="width: 100%">
			<el-table-column prop="id" label="ID" width="80" />
			<el-table-column prop="domain" label="加速域名" width="300"/>
			<el-table-column prop="origin_domain" label="源域名" width="300" />
			<el-table-column label="cdnauth" >
				<template #default="{ row }">
					{{ row.cdnauth }}
					<el-button v-if="row.cdnauth" @click="copyCdnAuth(row)">复制</el-button>
				</template>
			</el-table-column>
			<el-table-column label="cname">
				<template #default="{ row }">
					{{ row.cname }}
					<el-button v-if="row.cname" @click="copyCname(row)">复制</el-button>
				</template>
			</el-table-column>
			<el-table-column label="认证状态" width="140">
				<template #default="{ row }">
					{{ row.verify_status === 2 ? "已认证" : "未认证" }}
				</template>
			</el-table-column>
			<el-table-column label="部署状态" width="140">
				<template #default="{ row }">
					<div v-if="row.cdn_status == '1'">
						未创建
					</div>
					<div v-else-if="row.cdn_status == '2'">
						已启用
					</div>
					<div v-else-if="row.cdn_status == '3'">
						已停用
					</div>
					<div v-else-if="row.cdn_status == '4'">
						部署中
					</div>
					<div v-else>
						异常
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="300">
				<template #default="{ row }">
					<el-button type="primary" link @click="showEditDomainDialog(row)">编辑</el-button>

					<el-button v-if="row.verify_status != '2' && row.cdnauth==''" type="primary" link
						:loading="createCdnAuthLoading[row.id]" @click="createCdnAuthBtn(row)">生成认证</el-button>
					<el-button v-if="row.verify_status != '2' && row.cdnauth!=''" type="primary" link
						:loading="verifyCdnAuthLoading[row.id]" @click="verifyCdnAuthBtn(row)">域名认证</el-button>
					<el-button v-if="row.verify_status == '2' && row.cdn_status==1" type="primary" link
						:loading="createCdnLoading[row.id]" @click="createCdnBtn(row)">创建加速域名</el-button>
					<el-button v-if="row.verify_status == '2' && row.cdn_status==2" type="primary" link
						:loading="disableCdnLoading[row.id]" @click="disableCdnBtn(row)">禁用加速域名</el-button>
					<el-button v-if="row.verify_status == '2' && row.cdn_status==3" type="primary" link
						:loading="enableCdnLoading[row.id]" @click="enableCdnBtn(row)">启用加速域名</el-button>
					<el-button v-if="row.verify_status == '2' && (row.cdn_status==4||row.cdn_status==5)" type="primary"
						link :loading="reloadCdnLoading[row.id]" @click="reloadCdnBtn(row)">刷新状态</el-button>

					<el-button type="primary" link :loading="removeCdnLoading[row.id]" @click="removeCdnBtn(row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="pagination-container">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
				:page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
				@current-change="handleCurrentChange" />
		</div>

		<!-- 添加域名对话框 -->
		<el-dialog v-model="addDomainDialogVisible" title="添加" width="500px" :destroy-on-close="true">
			<el-form :model="addDomainForm" :rules="addDomainRules" ref="addDomainFormRef">
				<el-form-item label="加速域名" prop="domain" :label-width="'80px'">
					<el-input v-model="addDomainForm.domain" />
				</el-form-item>
				<el-form-item label="证书公钥" prop="certificate" :label-width="'80px'">
					<el-input :rows="2" v-model="addDomainForm.certificate" />
				</el-form-item>
				<el-form-item label="证书私钥" prop="private_key" :label-width="'80px'">
					<el-input :rows="2" v-model="addDomainForm.private_key" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addDomainDialogVisible = false">取消</el-button>
					<el-button type="primary" :loading="addDomainLoading" @click="handleAddDomain">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<!-- 编辑域名对话框 -->
		<el-dialog v-model="editDomainDialogVisible" title="编辑" width="500px" :destroy-on-close="true">
			<el-form :model="editDomainForm" :rules="editDomainForm" ref="editDomainFormRef">
				<el-form-item label="加速域名" prop="domain" :label-width="'80px'">
					<el-input v-model="editDomainForm.domain" disabled />
				</el-form-item>
				<el-form-item label="证书公钥" prop="certificate" :label-width="'80px'">
					<el-input :rows="2" v-model="editDomainForm.certificate" />
				</el-form-item>
				<el-form-item label="证书私钥" prop="private_key" :label-width="'80px'">
					<el-input :rows="2" v-model="editDomainForm.private_key" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editDomainDialogVisible = false">取消</el-button>
					<el-button type="primary" :loading="editDomainLoading" @click="handleEditDomain">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted } from "vue";
	import type { FormInstance, FormRules } from "element-plus";
	import { ElMessage } from "element-plus";
	import {
		getCdnHostList,
		addCdnHost,
		editCdnHost,
		createCdnAuth,
		verifyCdnAuth,
		createCdn,
		disableCdn,
		enableCdn,
		reloadCdn,
		removeCdn,
	} from "@/addon/htscrm/api/domainManagement";

	/**
	 * 接口定义
	 */
	// 域名列表项接口
	interface DomainItem {
		id : number; // 域名ID
		domain : string; // 加速域名
		certificate : string; // 证书
		private_key : string; // 证书密钥
		cdnauth : string; // cdnauth
		cname : string; // cname
		verify_status : number; //认证状态：2已认证 1未认证
		cdn_status : number; //认证状态：1未创建 2已启用 3已停用 4部署中 5异常
	}

	/**
	 * 数据定义
	 */

	// 搜索相关
	const searchDomain = ref(""); // 搜索关键词

	// 表格相关
	const tableData = ref<DomainItem[]>([]); // 表格数据
	const currentPage = ref(1); // 当前页码
	const pageSize = ref(10); // 每页条数
	const total = ref(0); // 总条数

	/**
	 * 对话框显示状态
	 */
	const addDomainDialogVisible = ref(false); // 添加域名对话框
	const editDomainDialogVisible = ref(false); // 编辑域名对话框

	/**
	 * 按钮loading状态
	 */
	const addDomainLoading = ref(false); // 添加域名按钮loading
	const editDomainLoading = ref(false); // 编辑域名按钮loading
	const createCdnAuthLoading = ref<Record<number, boolean>>({}); // 生成认证按钮loading
	const verifyCdnAuthLoading = ref<Record<number, boolean>>({}); // 域名认证按钮loading
	const createCdnLoading = ref<Record<number, boolean>>({}); // 创建加速域名按钮loading
	const disableCdnLoading = ref<Record<number, boolean>>({}); // 禁用加速域名按钮loading
	const enableCdnLoading = ref<Record<number, boolean>>({}); // 启用加速域名按钮loading
	const reloadCdnLoading = ref<Record<number, boolean>>({}); // 刷新状态按钮loading
	const removeCdnLoading = ref<Record<number, boolean>>({}); // 删除按钮loading

	/**
	 * 表单数据
	 */
	const addDomainForm = reactive({
		domain: "", // 域名名称
		certificate: '', // 证书
		private_key: '', // 证书密钥
	});

	const editDomainForm = reactive({
		id: 0,
		domain: "", // 域名名称
		certificate: '', // 证书
		private_key: '', // 证书密钥
	});

	/**
	 * 表单校验规则
	 */
	const addDomainRules = reactive<FormRules>({
		domain: [{ required: true, message: "请输入域名名称", trigger: "blur" }],
	});

	/**
	 * 表单引用
	 */
	const addDomainFormRef = ref<FormInstance>();
	const editDomainFormRef = ref<FormInstance>();

	/**
	 * 方法定义
	 */
	// 显示添加域名对话框
	const showAddDomainDialog = () => {
		addDomainDialogVisible.value = true;
	};
	// 显示编辑域名对话框
	const showEditDomainDialog = (oldData : { id : number; domain : string; certificate : string; private_key : string; }) => {
		editDomainDialogVisible.value = true;
		editDomainForm.id = oldData.id;
		editDomainForm.domain = oldData.domain;
		editDomainForm.certificate = oldData.certificate;
		editDomainForm.private_key = oldData.private_key;
	};

	// 复制文本到剪贴板（兼容性方法）
	const copyToClipboard = async (text : string) : Promise<boolean> => {
		// 方法1: 尝试使用现代 Clipboard API
		if (navigator.clipboard && navigator.clipboard.writeText) {
			try {
				await navigator.clipboard.writeText(text);
				return true;
			} catch (err) {
				console.warn('Clipboard API 失败:', err);
			}
		}

		// 方法2: 使用传统的 execCommand 方法作为备用方案
		try {
			const textArea = document.createElement('textarea');
			textArea.value = text;
			textArea.style.position = 'fixed';
			textArea.style.left = '-999999px';
			textArea.style.top = '-999999px';
			document.body.appendChild(textArea);
			textArea.focus();
			textArea.select();

			const successful = document.execCommand('copy');
			document.body.removeChild(textArea);

			if (successful) {
				return true;
			}
		} catch (err) {
			console.warn('execCommand 失败:', err);
		}

		return false;
	};

	// 复制CDN认证信息
	const copyCdnAuth = async (row : { cdnauth : string; domain : string }) => {
		try {
			const formattedText = `加速域名:${row.domain}\n主机记录:_cdnauth\n记录类型:TXT\n记录值:${row.cdnauth}`;
			const success = await copyToClipboard(formattedText);

			if (success) {
				ElMessage.success("CDN认证信息已复制到剪贴板");
			} else {
				ElMessage.error("复制失败，请手动复制");
				console.log('复制内容:', formattedText);
			}
		} catch (err) {
			console.error('复制失败:', err);
			ElMessage.error("复制失败，请手动复制");
		}
	}

	// 复制CNAME记录
	const copyCname = async (row : { cname : string; domain : string }) => {
		try {
			// 提取domain的前缀作为主机记录
			const hostRecord = row.domain.split('.')[0];
			const formattedText = `加速域名:${row.domain}\n主机记录:${hostRecord}\n记录类型:CNAME\n记录值:${row.cname}`;
			const success = await copyToClipboard(formattedText);

			if (success) {
				ElMessage.success("CNAME记录已复制到剪贴板");
			} else {
				ElMessage.error("复制失败，请手动复制");
				console.log('复制内容:', formattedText);
			}
		} catch (err) {
			console.error('复制失败:', err);
			ElMessage.error("复制失败，请手动复制");
		}
	}

	// 搜索处理
	const handleSearch = async () => {
		try {
			const res = await getCdnHostList({
				page: currentPage.value,
				limit: pageSize.value,
				domain: searchDomain.value,
			});
			tableData.value = res.data.data;
			total.value = res.data.total;
		} catch (e) {
			console.log(e);
		}
	};

	// 添加域名处理
	const handleAddDomain = async () => {
		if (!addDomainFormRef.value) return;
		addDomainLoading.value = true;
		try {
			await addDomainFormRef.value.validate(async (valid) => {
				if (valid) {
					const res = await addCdnHost(addDomainForm);
					if (res.code === 1) {
						ElMessage.success("添加域名成功");
						addDomainDialogVisible.value = false;
						handleSearch();
					} else {
						ElMessage.error("添加域名失败");
					}
				}
			});
		} finally {
			addDomainLoading.value = false;
		}
	};

	// 编辑域名处理
	const handleEditDomain = async () => {
		editDomainLoading.value = true;
		try {
			const res = await editCdnHost(editDomainForm);
			if (res.code === 1) {
				ElMessage.success("编辑域名成功");
				editDomainDialogVisible.value = false;
				handleSearch();
			} else {
				ElMessage.error("编辑域名失败");
			}
		} finally {
			editDomainLoading.value = false;
		}
	};

	// 创建加速域名认证cdnauth
	const createCdnAuthBtn = async (row : { id : number }) => {
		createCdnAuthLoading.value[row.id] = true;
		try {
			const res = await createCdnAuth({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("创建cdnauth成功");
				handleSearch();
			} else {
				ElMessage.error("创建cdnauth失败");
			}
		} finally {
			createCdnAuthLoading.value[row.id] = false;
		}
	}

	// 认证加速域名
	const verifyCdnAuthBtn = async (row : { id : number }) => {
		verifyCdnAuthLoading.value[row.id] = true;
		try {
			const res = await verifyCdnAuth({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("认证cdnauth成功");
				handleSearch();
			} else {
				ElMessage.error("认证cdnauth失败");
			}
		} finally {
			verifyCdnAuthLoading.value[row.id] = false;
		}
	}

	// 创建加速域名
	const createCdnBtn = async (row : { id : number }) => {
		createCdnLoading.value[row.id] = true;
		try {
			const res = await createCdn({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("创建成功");
				handleSearch();
			} else {
				ElMessage.error("创建失败");
			}
		} finally {
			createCdnLoading.value[row.id] = false;
		}
	}

	// 禁用加速域名
	const disableCdnBtn = async (row : { id : number }) => {
		disableCdnLoading.value[row.id] = true;
		try {
			const res = await disableCdn({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("禁用成功");
				handleSearch();
			} else {
				ElMessage.error("禁用失败");
			}
		} finally {
			disableCdnLoading.value[row.id] = false;
		}
	}

	// 启用加速域名
	const enableCdnBtn = async (row : { id : number }) => {
		enableCdnLoading.value[row.id] = true;
		try {
			const res = await enableCdn({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("启用成功");
				handleSearch();
			} else {
				ElMessage.error("启用失败");
			}
		} finally {
			enableCdnLoading.value[row.id] = false;
		}
	}

	// 刷新加速域名
	const reloadCdnBtn = async (row : { id : number }) => {
		reloadCdnLoading.value[row.id] = true;
		try {
			const res = await reloadCdn({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("刷新成功");
				handleSearch();
			} else {
				ElMessage.error("刷新失败");
			}
		} finally {
			reloadCdnLoading.value[row.id] = false;
		}
	}
	// 删除加速域名
	const removeCdnBtn = async (row : { id : number }) => {
		removeCdnLoading.value[row.id] = true;
		try {
			const res = await removeCdn({
				id: row.id,
			});
			if (res.code === 1) {
				ElMessage.success("删除成功");
				handleSearch();
			} else {
				ElMessage.error("删除失败");
			}
		} finally {
			removeCdnLoading.value[row.id] = false;
		}
	}


	// 表格分页大小改变处理
	const handleSizeChange = async (val : number) => {
		pageSize.value = val;
		handleSearch();
	};

	// 表格页码改变处理
	const handleCurrentChange = async (val : number) => {
		currentPage.value = val;
		handleSearch();
	};

	/**
	 * 生命周期钩子
	 */
	// 组件挂载时初始化数据
	onMounted(async () => {
		handleSearch();
	});
</script>

<style lang="scss" scoped>
	.domain-management {
		padding: 20px;
		background-color: #fff;
		border-radius: 10px;

		// 操作按钮行样式
		.operation-row {
			margin-bottom: 20px;
		}

		// 搜索行样式
		.search-row {
			display: flex;
			align-items: center;
			margin-bottom: 20px;
			gap: 20px;

			.stat-item {
				min-width: 150px;
			}

			.search-input {
				width: 300px;
			}
		}

		// 分页容器样式
		.pagination-container {
			margin-top: 20px;
			display: flex;
			justify-content: flex-end;
		}

		// 对话框底部按钮样式
		.dialog-footer {
			display: flex;
			justify-content: flex-end;
			gap: 10px;
		}
	}
</style>